//
//  RJCheckDataBottomTableVC.m
//  AirQuality
//
//  Created by Po on 15/3/16.
//  Copyright (c) 2015年 Po. All rights reserved.
//

#import "RJCheckDataBottomTableVC.h"
#import "RJCheckDataBottomTableModel.h"
#import "RJCheckDataFitCell.h"
#import "RJDetailBox.h"
#import "RJCheckDetailVC.h"
#import "RJCheckReasonVC.h"

static NSUInteger markCount;
@interface RJCheckDataBottomTableVC () <RJCheckDataFitCellDelegate, RJDetailBoxDelegate, RJCheckDetailVCDelegate, CheckReasonDelegate>

@property (retain, nonatomic) UIImageView * selectImage;                 //选中背景
@property (retain, nonatomic) RJDetailBox * detailBox;                   //详情弹框
@property (retain, nonatomic) RJCheckDataCellButton * currentButton;     //当前选中按钮

@property (retain, nonatomic) RJCheckDataBottomTableModel * model;       //数据
@property (retain, nonatomic) NSMutableArray * problemTimes;             //问题事件

@property (assign, nonatomic) BOOL isShowBlue;                           //蓝白行
@property (assign) NSUInteger i;

- (void)initData;
- (void)initInterface;
@end

@implementation RJCheckDataBottomTableVC

- (instancetype)init
{
    self = [super init];
    if (self) {
        _i = 0;
        _onlyShow = NO;
        _near24Hour = NO;
    }
    return self;
}

- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
//    NSLog(@"%ld",markCount);
//    self.countBlock(markCount);
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initData];
    [self initInterface];
}

#pragma mark - user-defined initialization function
- (void)initData
{
    _showProblem = NO;
    _isShowBlue = NO;
    _model = [[RJCheckDataBottomTableModel alloc] init];
    _model.startTime = 0;
    _problemTimes = [[NSMutableArray alloc] init];
}

- (void)initInterface
{
    //self init
    [self.tableView setBackgroundColor:[UIColor clearColor]];
    [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    
    //all init
    [self.view addSubview:[self getSelectImage]];
}

- (UIImageView *)getSelectImage
{
    if (!_selectImage) {
        _selectImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth / (_model.cellKeys.count + 1), 44)];
        [_selectImage setImage:[UIImage imageNamed:@"dataSelectHighLight"]];
        [_selectImage setHidden:YES];
    }
    return _selectImage;
}

- (void)setNear24Hour:(BOOL)near24Hour
{
    _near24Hour = near24Hour;
    if (_near24Hour) {
        _model.startTime = [[RJTools getTimeWithFormat:@"hh"] integerValue];
    }
}
#pragma mark - function
- (void)setCellBlueBack:(BOOL)isShow
{
    _isShowBlue = isShow;
}

- (CGRect)getDetailBoxRect:(CGRect)rect
{
    CGFloat length = rect.origin.y + rect.size.height;
    if (length > ScreenHeight) {
        //当前Y减去按钮高度为上方
        rect.origin.y -= (rect.size.height + 40);
    }
    return rect;
}

- (void)setData:(NSArray *)data time:(NSUInteger)time cellKeys:(NSArray *)cellKeys
{
    markCount = 0;
    NSArray * array = @[@"so2",@"no2",@"co",@"o3",@"pm10",@"pm2_5"];
    NSMutableArray * probleamKeys = [NSMutableArray arrayWithArray:array];
    _model.data = [NSMutableArray arrayWithArray:data];
    _model.time = time;
    _model.cellKeys = [NSArray arrayWithArray:cellKeys];
    for (NSDictionary * dic in data) {
        for (NSUInteger j = 0; j < probleamKeys.count; j ++) {
            NSString * markKey = [NSString stringWithFormat:@"%@_mark",probleamKeys[j]];
            NSString * mark = dic[markKey];
            if (![mark  isEqual: @""]) {
                markCount ++;
            }
        }
    }
    NSString * string = [NSString stringWithFormat:@"%ld",markCount];
   [[NSNotificationCenter defaultCenter] postNotificationName:@"CheckProplemCount" object:string];
    [self.tableView reloadData];
}

- (void)setData1:(NSArray *)data time1:(NSUInteger)time cellKeys1:(NSArray *)cellKeys{
    _model.data = [NSMutableArray arrayWithArray:data];
    _model.time = time;
    _model.cellKeys = [NSArray arrayWithArray:cellKeys];
    [self showProblem1];
}
- (void)setCellKeys:(NSArray *)keys
{
    if (_delegate) {
        [_delegate CheckDataBottomTable:self showTypes:keys];
    }
    _selectKeysArray = [NSArray arrayWithArray:keys];
    [self updateKeys:keys];
}

- (void)updateKeys:(NSArray *)keys
{
    _model.cellKeys = [NSArray arrayWithArray:keys];
    _model.headCellTitles = [RJTools getTrueCellTitleWithKeys:keys];
    CGRect rect = self.tableView.frame;
    self.tableView = [[UITableView alloc] initWithFrame:rect style:UITableViewStylePlain];
    [[self getSelectImage] removeFromSuperview];
    _selectImage = nil;
    [self.view insertSubview:[self getSelectImage] aboveSubview:self.tableView];
    [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [self.tableView setBackgroundColor:[UIColor clearColor]];
    [self.tableView reloadData];
}

- (void)showProblem1{
 [_problemTimes removeAllObjects];
 NSArray * array = @[@"so2",@"no2",@"co",@"o3",@"pm10",@"pm2_5"];
 NSMutableArray * probleamKeys = [NSMutableArray arrayWithArray:array];
    NSMutableArray * tempKeys = [NSMutableArray arrayWithArray:probleamKeys];
    for (NSUInteger i = 0; i < _model.data.count; i ++) {
        NSDictionary * dic = _model.data[i];
        BOOL isCheckTime = NO;
        for (NSUInteger j = 0; j < probleamKeys.count; j ++) {
            NSString * markKey = [NSString stringWithFormat:@"%@_mark",probleamKeys[j]];
            NSString * mark = dic[markKey];
            //判断是否为无效数据
            if ([mark isEqualToString:@""]) {
                continue;
            }
            else{
                if (![tempKeys[j] isEqualToString:@""]) {
                    
                    tempKeys[j] = @"";
                }
                //是否已经保留了当前事件
                if (!isCheckTime) {
                    [_problemTimes addObject:@(i)];
                    isCheckTime = YES;
                }
            }
        }
    }
    //删选出问题Key
    for (NSString * key in tempKeys) {
        if ([probleamKeys indexOfObject:key] != NSNotFound) {
            [probleamKeys removeObject:key];
        }
    }
    [self setCellKeys:probleamKeys];
    if (_delegate) {
        [_delegate CheckDataBottomTable:self showTypes:probleamKeys];
    }


}
- (void)showProblem:(BOOL)isShow
{
    if (_showProblem == isShow) {
        return;
    }
    _showProblem = isShow;
    [_problemTimes removeAllObjects];
    
    NSMutableArray * probleamKeys = [NSMutableArray arrayWithArray:@[@"so2",@"no2",@"co",@"o3",@"pm10",@"pm2_5"]];
    if (_showProblem) {
        NSMutableArray * tempKeys = [NSMutableArray arrayWithArray:probleamKeys];
        for (NSUInteger i = 0; i < _model.data.count; i ++) {
            NSDictionary * dic = _model.data[i];
            BOOL isCheckTime = NO;
            for (NSUInteger j = 0; j < probleamKeys.count; j ++) {
                NSString * markKey = [NSString stringWithFormat:@"%@_mark",probleamKeys[j]];
                NSString * mark = dic[markKey];
                //判断是否为无效数据
                if ([mark isEqualToString:@""]) {
                    continue;
                }
                else{
                    if (![tempKeys[j] isEqualToString:@""]) {
                        
                                tempKeys[j] = @"";
                    }
                        //是否已经保留了当前事件
                    if (!isCheckTime) {
                        [_problemTimes addObject:@(i)];
                        isCheckTime = YES;
                    }

                }
//                } else if (([mark rangeOfString:@"RM"].location != NSNotFound) || ([mark rangeOfString:@"H"].location != NSNotFound) || [mark rangeOfString:@"HSp"].location != NSNotFound) {
////                    if ([mark rangeOfString:@"HSp"].location != NSNotFound) {
////                        continue;
////                    } else {
//                        if (![tempKeys[j] isEqualToString:@""]) {
//                            tempKeys[j] = @"";
//                        }
//                        //是否已经保留了当前事件
//                        if (!isCheckTime) {
//                            [_problemTimes addObject:@(i)];
//                            isCheckTime = YES;
//                        }
//                    }
//                } else {
//                    continue;
//                }
            }
        }
        
        //删选出问题Key
        for (NSString * key in tempKeys) {
            if ([probleamKeys indexOfObject:key] != NSNotFound) {
                [probleamKeys removeObject:key];
            }
        }
    }
    
    [self setCellKeys:probleamKeys];
    if (_delegate) {
        [_delegate CheckDataBottomTable:self showTypes:probleamKeys];
    }
    
    [self.tableView reloadData];
}
/**按下了组头*/
- (void)pressSectionView
{
    [self.tableView setContentOffset:CGPointZero animated:YES];
}

/**跳转审核信息页面*/
- (void)goCheckDataView
{
    RJCheckReasonVC * checkReasonVC = [[RJCheckReasonVC alloc] init];
    [checkReasonVC setDelegate:self];
    [checkReasonVC setCheckData:_model.checkData];
    [sysWindow addSubview:checkReasonVC.view];
    [self addChildViewController:checkReasonVC];
}

#pragma mark - Table view data source

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return NO;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (_showProblem) {
        return _problemTimes.count;
    }
    
    return 24;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 44;
}

- (RJCheckDataFitCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString * cellIdent = @"RJCheckDataFitCell";
    RJCheckDataFitCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdent];
    if (!cell) {
        cell = [[RJCheckDataFitCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"RJCheckDataFitCell"];
        [cell setButtonNum:_model.cellKeys.count + 1];
        cell.backgroundColor = [UIColor clearColor];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.contentView.backgroundColor = [UIColor clearColor];
        cell.selectedBackgroundView = [[UIView alloc] init];
        [cell setDelegate:self];
    }
    //计算时间
    NSInteger time;
    if (_showProblem) {
        time = [_problemTimes[indexPath.row] integerValue];
    } else {
        time = indexPath.row + _model.startTime;
    }
    
    if (++time >= 24) {
        time -= 24;
    }
    NSString * timeString = [NSString stringWithFormat:@"%2ld时",time];
    
    [cell.allButtons[0] setTitle:timeString forState:UIControlStateNormal];
    NSUInteger arrayCount = _showProblem ? ([_problemTimes[indexPath.row] integerValue]):indexPath.row;
    NSDictionary * dic = _model.data[arrayCount];
    //获取数值按钮
    
    NSArray * buttons = [cell.allButtons subarrayWithRange:NSMakeRange(1, cell.allButtons.count - 1)];
    //标示按钮（方便后面计算），并设置值
//    _model.cellKeys = @[@"so2",@"no2",@"co",@"o3",@"pm10",@"pm2_5"];
    for (NSUInteger i = 0; i < cell.allButtons.count - 1; i ++) {
        [self setCellButton:buttons[i] dataDic:dic key:_model.cellKeys[i]];
    }
    return cell;
}

- (void)setCellButton:(RJCheckDataCellButton *)button dataDic:(NSDictionary *)dataDic key:(NSString *)key
{
    
    NSString * markString = [dataDic objectForKey:[NSString stringWithFormat:@"%@_mark",key]];
    if (!markString) {
        markString = @"";
    }
   
    [button setMark:markString];
    [button setBackgroundColor:[self getColorWithNewMark:markString]];
    if (button.backgroundColor != [UIColor clearColor]) {
        button.tag = 1000 + _i;
        _i ++;
    }
    if ([key isEqualToString:@"co"] || [key isEqualToString:@"CO"]) {
        NSString * num = [NSString stringWithFormat:@"%.1f",[dataDic[key] floatValue]];
        [button setTitle:num forState:UIControlStateNormal];
        return;
    }
    [button setTitle:GetStringWithNum(dataDic[key]) forState:UIControlStateNormal];
}


#pragma mark - RJCheckDataCellDelegate
/**点击对应的数值时*/
- (void)RJCheckDataFitCellDidSelect:(RJCheckDataCellButton *)button cell:(RJCheckDataFitCell *)cell
{
    if (_onlyShow) {
        return;
    }
    
    _currentButton = button;
    //设置选中背景
    [_selectImage setHidden:NO];
    CGRect rect = _selectImage.frame;
    rect.origin.x = button.frame.origin.x;
    rect.origin.y = cell.frame.origin.y;
    [_selectImage setFrame:rect];
    
    //显示对应的弹框
//    NSArray * titleArray = [NSArray array];
//    if ([RJUserData defaultRJUserData].isProvince) {
//        titleArray = @[@"数据详情"];
//    }else{
//       titleArray = @[@"数据详情",@"数据审核"]; 
//    }
    NSArray * titleArray = @[@"数据详情",@"数据审核"];
    CGRect detailBoxRect = CGRectMake(
                                      button.frame.origin.x,
                                      _selectImage.frame.origin.y + button.frame.size.height + 140 - self.tableView.contentOffset.y,
                                      100,
                                      50 * titleArray.count
                                      );
    NSString * timeButtonString = [[cell.allButtons[0] titleLabel] text];
    NSRange timeRange = [timeButtonString rangeOfString:@"时"];
    timeButtonString = [timeButtonString substringToIndex:timeRange.location];
    BOOL isYesterday = YES;
    if ([timeButtonString integerValue] < 10) {
        timeButtonString = [NSString stringWithFormat:@"0%ld",[timeButtonString integerValue]];
        if ([timeButtonString integerValue] == 0) {
            isYesterday = NO;
        }
    } else {
        timeButtonString = [NSString stringWithFormat:@"%ld",[timeButtonString integerValue]];
    }
    
    NSString * timeString = [RJTools getTimeWithFormat:@"yyyy-MM-dd" time:(isYesterday ? YesterdayDate : [NSDate date])];
    //获取数据
    NSString * time = [NSString stringWithFormat:@"%@ %@:00:00",timeString, timeButtonString];
    NSString * type = _model.headCellTitles[button.typeNumber];
    NSString * type_mark = button.mark;
    NSString * stationCode = _stationCode;
    NSString * value = button.titleLabel.text;
//    NSRange range = [_stationName rangeOfString:@"- "];
    
    _model.checkData = @{@"timepoint":time, @"GasType":type,@"OldMark":type_mark,@"stationcode":stationCode,@"value":value,@"stationName":_stationName};
    //促使详情弹框
    detailBoxRect = [self getDetailBoxRect:detailBoxRect];
    _detailBox = [RJDetailBox detailBoxWithBoxFrame:detailBoxRect detail:titleArray];
    [_detailBox setDelegate:self];
    [_detailBox show];
}

#pragma mark - RJDetailBoxDelegate
- (void)RJDetailBoxDelegate:(RJDetailBox *)detailBox DidSelected:(NSUInteger)row
{
    detailBox = nil;
    //是否选择自定义理由
    if (row == 0) {
        RJCheckDetailVC * checkDetailView = [[RJCheckDetailVC alloc] init];
        [checkDetailView setData:_model.checkData];
        [checkDetailView setDelegate:self];
        [sysWindow addSubview:checkDetailView.view];
        [self addChildViewController:checkDetailView];
    } else {
        [self goCheckDataView];
    }
}

#pragma mark - RJCheckDetailVCDelegate
- (void)didSelect:(RJCheckDetailVC *)checkVC Button:(NSUInteger)buttonNum
{
    [checkVC removeSelf];
    [self goCheckDataView];
}


#pragma mark - CheckReasonDelegate
- (void)checkReason:(RJCheckReasonVC *)checkreasonVC value:(NSNumber *)value newMark:(NSString *)mark isChange:(BOOL)change
{
    if (!change) {
        return;
    }
    [_currentButton setMark:mark];
    [_currentButton setTitle:GetStringWithNum(value) forState:UIControlStateNormal];
    [_currentButton setBackgroundColor:[self getColorWithNewMark:mark]];
    RJCheckDataFitCell * cell = (RJCheckDataFitCell *)_currentButton.superview.superview;
    NSIndexPath * indexPath = [self.tableView indexPathForCell:cell];
    NSMutableDictionary * dic = [NSMutableDictionary dictionaryWithDictionary:_model.data[indexPath.row]];
    NSUInteger typeNumber = _currentButton.typeNumber;
    NSString * key = _model.cellKeys[typeNumber];
    [dic setObject:value forKey:key];
    NSString * keymark = [NSString stringWithFormat:@"%@MARK",key];
    [dic setObject:mark forKey:keymark];
    _model.data[indexPath.row] = dic;
    [RJTools showTitle:@"提示" msg:@"操作成功！" cancelString:@"知道了" vc:self];
}

/**根据mark返回相对应的背景色*/
- (UIColor *)getColorWithNewMark:(NSString *)mark
{
     if ([mark isEqualToString:@""]) {
        return [UIColor clearColor];
    
     } else if (([mark rangeOfString:@"RM"].location != NSNotFound) || ([mark rangeOfString:@"H"].location != NSNotFound) ) {

         if ([mark rangeOfString:@"HSp"].location != NSNotFound) {
             return GetRGBColor(129, 220, 80, 1);
         } else {
             return GetRGBColor(255, 151, 152, 1);
         }
         
     } else {

        return GetRGBColor(129, 220, 80, 1);
     }
}
@end
